package json;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONWriter;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/*
* FASTJSON2实现java对象和JSON数据的互转
*   1.将java对象(普通对象，集合，map)转换为json字符串
*       JSON.toJSONString()
*   2.将json字符串转化为java对象
*       JSON.parseObject()
*   3.将含有数组的json字符串解析成java的集合对象
*       JSONArray.parseArray()
*
*
* */
public class JSONTest02 {
    /*将java对象转化为JSON格式*/
    @Test
    public void testObjectToJson() {
        List<Item> items = Arrays.asList(
                new Item("ITEM001", 2, 50.0),
                new Item("ITEM002", 1, 150.75)
        );

        Purchase purchase = new Purchase("ORD12345", "USR001", 250.75, items);
        Student student = new Student(20131210, "无忌", "男", 25);
        System.out.println(JSON.toJSONString(purchase));
    }

    /*将JSON格式转化为java对象*/
    @Test
    public void testJsonToObject() {
        String jsonStr = "{\"orderId\": \"ORD12345\",  \"userId\": \"USR001\",  \"totalAmount\": 250.75,\"items\": [{ \"itemId\" : \"ITEM001\" , \"quantity\": 2, \"price\": 50.0 }, { \"itemId \": \"ITEM002\", \"quantity\": 1 , \"price\" : 150.75 } ] }";
        Purchase purchase = JSON.parseObject(jsonStr, Purchase.class);
        System.out.println(purchase);
    }
    /*将一个集合转换成json*/
    @Test
    public void testListToJSON() {
        List<Student> students = Arrays.asList(
                new Student(20131210, "无忌", "男", 25),
                new Student(20131223, "敏敏", "女", 20)
        );
        System.out.println(JSON.toJSONString(students));
        System.out.println(JSON.toJSONString(students, JSONWriter.Feature.PrettyFormat));
    }

    /*将一个json转换成集合*/
    @Test
    public void testJSONtToList() {
        String jsonStr = "[{\"age\":25,\"gender\":\"男\",\"sname\":\"无忌\",\"sno\":20131210},{\"age\":20,\"gender\":\"女\",\"sname\":\"敏敏\",\"sno\":20131223}]";
        JSONArray.parseArray(jsonStr, Student.class).forEach(System.out::println);
    }

    /*将map转换成json串*/
    @Test
    public void testMapToJson() {
        List<Student> students = Arrays.asList(
                new Student(20131210, "无忌", "男", 25),
                new Student(20131223, "敏敏", "女", 20)
        );
        Map<String, Student> map = students.stream().collect(Collectors.toMap(stu -> stu.getSno() + "", stu -> stu));

        System.out.println(JSON.toJSONString(students));
        System.out.println(JSON.toJSONString(students, JSONWriter.Feature.PrettyFormat));
    }
}
